<template>
	<view>
		<image :src="src" mode="" class="downImg"></image>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				src: ""
			}
		},
		onLoad(options) {
			this.src = options.src
			this.downImg()
		},
		methods: {
			async downImg() {
				let ImgUrl = ""
				await this.base64ToTempFilePath(this.src)
					.then((tempFilePath) => {
						ImgUrl = tempFilePath;
						console.log("临时文件路径:", tempFilePath);
					})
				wx.saveImageToPhotosAlbum({
					filePath: ImgUrl, //这是把临时文件 保存到 相册, 收工
					success: res => {
						wx.showToast({
							title: '下载成功，请到相册查看',
							duration: 2000,
							icon: 'none'
						});
						setTimeout(function() {
							wx.navigateBack({
								delta: 1
							})
						}, 2000) //延迟时间
					},
					fail: error => {
						wx.showToast({
							title: '下载失败'
						})
						setTimeout(function() {
							wx.navigateBack({
								delta: 1
							})
						}, 2000) //延迟时间
					}
				})
			},
			base64ToTempFilePath(base64Data) {
				return new Promise((resolve, reject) => {
					try {
						// 提取 Base64 编码部分
						const base64 = base64Data.replace(/^data:image\/\w+;base64,/, "");
						// let bolean
						// 获取文件系统管理器

						const fs = wx.getFileSystemManager();
						// 创建临时文件路径
						const tempFilePath =
							wx.env.USER_DATA_PATH + "/temp_image_" + Date.now() + ".png";

						// 将 Base64 数据转为 ArrayBuffer
						const arrayBuffer = wx.base64ToArrayBuffer(base64);

						// 写入文件
						fs.writeFile({
							filePath: tempFilePath,
							data: arrayBuffer,
							encoding: "binary",
							success: () => {
								resolve(tempFilePath); // 成功时返回临时文件路径
							},
							fail: (err) => {
								reject("文件写入失败: " + err);
							},
						});
					} catch (error) {
						reject("转换失败: " + error);
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	.downImg {
		display: block;
		max-width: 90%;
		margin: 5% auto 0;
	}
</style>